﻿using HZH_Controls;
using HZH_Controls.Forms;
using System;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace Listener_SMS
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }
        private SmsObserver smsObserver;
        /// <summary>
        /// 是否连接上db数据库
        /// </summary>
        private bool isCoom;
        /// <summary>
        /// 
        /// </summary>
        private static string lockConf = "c:\\system\\listenersms\\lock";

        /// <summary>
        /// 公司标识
        /// </summary>
        private static string companyCode = "";

        /// <summary>
        /// 初始化配置
        /// </summary>
        private void InitCfg()
        {

            //初始化公司配置
            //if (File.Exists(lockConf))
            //{
            //    companyCode = File.ReadAllText(lockConf);
            //    if (String.IsNullOrEmpty(companyCode))
            //    {
            //        ControlHelper.ThreadInvokerControl(this, () =>
            //        {
            //            FrmTips.ShowTipsError(this, "配置文件丢失，请重新安装软件");
            //        });
            //        return;
            //    }
            //}
            //else
            //{
            //    ControlHelper.ThreadInvokerControl(this, () =>
            //    {
            //        FrmTips.ShowTipsError(this, "配置文件丢失，请重新安装软件");
            //    });
            //    return;
            //}

            //初始化历史access数据库路径
            string logPath = getAccessDbConfigPath();
            ControlHelper.ThreadInvokerControl(this, () =>
            {
                ucTextBoxEx1.InputText = DdDbFileExists(ReadPath(logPath));
            });
        }

        #region 读取叮叮摩卡ACCESS DB========实现自动登录操作=========================================
        private string getAccessDbConfigPath()
        {
            string logPath = Application.StartupPath + "\\data\\";
            if (!Directory.Exists(logPath))
            {
                Directory.CreateDirectory(logPath);
            }
            logPath += StringConst.MainMessage.MAIN_DD_ACCESS_PATH;
            return logPath;
        }

        /// <summary>
        /// 链接access数据库-叮叮
        /// </summary>
        public bool coomDb(string path)
        {
            try
            {
                string accessPath = "";
                string logPath = getAccessDbConfigPath();
                if (!string.IsNullOrWhiteSpace(path))
                {
                    accessPath = path;
                    StreamWriter sw = new StreamWriter(logPath, false);
                    sw.WriteLine(path);
                    sw.Close();
                }
                else
                {
                    accessPath = ReadPath(logPath);
                }
                accessPath = this.DdDbFileExists(accessPath + "MMS.mdb");
                if (!string.IsNullOrWhiteSpace(accessPath))
                {
                    DbHelperACE.connectionString = string.Format(Properties.Resources.AceConnStr, accessPath);
                    //注册短信观察者 
                    smsObserver = SmsObserver.init(accessPath).setListener(new SmsObserver.ListenerHandler(listenerSms));
                    bool isRegister = smsObserver.Register();
                    if (isRegister)
                    {
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return false;
        }

        /// <summary>
        /// 判断叮叮猫机数据库是否存在
        /// </summary>
        /// <param name="path"> 路径 </param>
        /// <returns></returns>
        private string DdDbFileExists(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                path = "C:\\Program Files (x86)\\叮叮科技\\叮叮摩卡\\MMS.mdb";
                bool isExists = File.Exists(path);
                if (!isExists)
                {
                    path = "C:\\Program Files\\叮叮科技\\叮叮摩卡\\MMS.mdb";
                    isExists = File.Exists(path);
                    if (!isExists)
                    {
                        path = "";
                    }
                }
            }
            return path;
        }

        /// <summary>
        /// 获取叮叮摩卡ACCESS路径内容
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public string ReadPath(string path)
        {
            string returnPath = "";
            if (!string.IsNullOrWhiteSpace(path) && File.Exists(path))
            {
                StreamReader sr = null;
                try
                {
                    sr = new StreamReader(path, Encoding.UTF8);
                    String line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        returnPath = line.ToString();
                    }
                }
                catch (IOException e)
                {
                }
                finally
                {
                    sr.Close();
                }
            }

            return returnPath;
        }

        #endregion

        private void Main_Load(object sender, EventArgs e)
        {
            ControlHelper.ThreadRunExt(this, () =>
            {
                InitCfg();
                this.isCoom = coomDb(ucTextBoxEx1.InputText);
                ControlHelper.ThreadInvokerControl(this, () =>
                {
                    if (this.isCoom)
                    {
                        this.lblstate.Text = "正在运行";
                    }
                    else
                    {
                        this.lblstate.Text = "停止";
                    }
                });
            }, null, this);
        }

        /// <summary>
        /// 监听最新消息
        /// </summary>
        /// <param name="dtNowSms">消息内容集合</param>
        private void listenerSms(DataTable dtNowSms)
        {

            for (var i = 0; i < dtNowSms.Rows.Count; i++)
            {
                DataRow dataRow = dtNowSms.Rows[i];
                bool isYzmSms = chkYzmSms(dataRow["MsgTitle"].ToString());
                if (isYzmSms)
                {
                    HqHttpClient hqHttp = new HqHttpClient();
                    //发送
                    ;
                    HttpWebResponse httpWeb = hqHttp.post(this.ucTextBoxEx2.InputText, assemblyParam(dataRow));
                    string sdfsd = hqHttp.responseToString(httpWeb);
                    Console.WriteLine(sdfsd);
                }
            }
        }

        /// <summary>
        /// 组装参数
        /// </summary>
        /// <param name="dataRow"></param>
        /// <returns></returns>
        private string assemblyParam(DataRow dataRow)
        {
            string param = "sender=" + dataRow["Sender"];
            //param += "&MsgType=" + dataRow["MsgType"];
            param += "&msgContent=" + dataRow["MsgTitle"];
            param += "&sendTime=" + dataRow["MsgArrivedTime"];
            //param += "&imsi=" + dataRow["imsi"];
            //param += "&imei=" + dataRow["imei"];
            param += "&mobile=" + dataRow["shoujihao"];
            //param += "&ccid=" + dataRow["ccid"];
            return param;
        }

        /// <summary>
        /// 验证码短信校验
        /// </summary>
        /// <param name="content">内容</param>
        /// <returns></returns>
        private bool chkYzmSms(string content)
        {
            bool isYzmSms = chkYzmSms(6, content);
            if (!isYzmSms)
            {
                isYzmSms = chkYzmSms(4, content);
            }
            return isYzmSms;
        }

        /// <summary>
        /// 验证码短信校验
        /// </summary>
        /// <param name="length">长度：验证码一般为4位或6位</param>
        /// <param name="content">内容</param>
        /// <returns></returns>
        private bool chkYzmSms(int length, string content)
        {
            Regex regex = new Regex("(?<![0-9])([0-9]{" + length + "})(?![0-9])");
            MatchCollection matchs = regex.Matches(content);
            foreach (Match match in matchs)
            {
                return true;
            }
            return false;
        }

        private void ucBtnExt1_BtnClick(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.ShowNewFolderButton = false;
            dialog.SelectedPath = ucTextBoxEx1.InputText;
            dialog.Description = "请选择叮叮安装路径";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                if (string.IsNullOrEmpty(dialog.SelectedPath))
                {
                    MessageBox.Show("文件夹路径不能为空", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                    return;
                }
                ucTextBoxEx1.InputText = dialog.SelectedPath + "\\";
                //保存到配置文件，下次启动默认选择路径
                this.isCoom = false;
            }
        }

        private void ucBtnExt1_BtnClick_1(object sender, EventArgs e)
        {
            if (!this.isCoom)
            {
                this.isCoom = coomDb(ucTextBoxEx1.InputText);
                if (isCoom)
                {
                    FrmTips.ShowTipsSuccess(this, "链接成功");
                    this.lblstate.Text = "正在运行";
                }
                else
                {
                    FrmTips.ShowTipsError(this, "绑定叮叮失败，请检查是否选中叮叮安装目录");
                    this.lblstate.Text = "停止";
                }
            }
            else
            {
                FrmTips.ShowTipsError(this, "叮叮已经连接成功，无须重复连接");
            }
        }

        bool KaiGuan = false;
        Point startPoint;
        private void panel3_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                KaiGuan = true;
                startPoint = new Point(-e.X, -e.Y);
            }
        }

        private void panel3_MouseMove(object sender, MouseEventArgs e)
        {
            if (KaiGuan)
            {
                Point mousePos = Control.MousePosition;//665,544
                mousePos.Offset(startPoint.X, startPoint.Y);
                Location = mousePos;
            }
        }

        private void panel3_MouseUp(object sender, MouseEventArgs e)
        {
            KaiGuan = false;
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void 显示窗体ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
        }
        private static bool EXIT_STATE = false;
        private void 隐藏窗体ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("退出程序后，服务将不可用，是否继续退出？", "退出程序", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                EXIT_STATE = true;
                Application.Exit();
            }
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!EXIT_STATE)
            {
                e.Cancel = true;
                this.Hide();
            }
        }

        private void ucBtnExt2_BtnClick_1(object sender, EventArgs e)
        {
            try
            {
                if (this.isCoom)
                {
                    if (string.IsNullOrEmpty(this.textBoxEx2.Text)) {
                        FrmTips.ShowTipsError(this, "手机号码不能为空");
                        return;
                    }
                    if (string.IsNullOrEmpty(this.textBoxEx1.Text))
                    {
                        FrmTips.ShowTipsError(this, "短信内容不能为空");
                        return;
                    }
                    smsObserver.TestInsert(this.textBoxEx2.Text, this.textBoxEx1.Text);
                    FrmTips.ShowTipsSuccess(this, "发送成功：" + this.textBoxEx2.Text);
                }
                else {
                    FrmTips.ShowTipsError(this, "绑定叮叮失败，请检查是否选中叮叮安装目录");
                }
            }
            catch {
                FrmTips.ShowTipsError(this, "发送异常");
            }
        }
    }
}